package cn.myzf.netty.client.handler;


import com.alibaba.fastjson.JSON;
import com.hs.netty.common.entity.NettyMessageDO;
import com.hs.netty.common.protobuf.Command;
import com.hs.netty.common.protobuf.Message;
import com.hs.netty.common.util.ReflectionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;


public class AuthClientHandler extends SimpleChannelInboundHandler<Message> {
    public Logger log = LoggerFactory.getLogger(this.getClass());
    private final static String CLIENTID = ReflectionUtil.getValue("spring.netty.clientId");
    private final static String DEVICENAME = ReflectionUtil.getValue("spring.netty.deviceName");
    /**
     * （1） 连接成功后，向server发送认证消息消息
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        NettyMessageDO nettyMessageDO = new NettyMessageDO();
        nettyMessageDO.setClientName(CLIENTID);
        nettyMessageDO.setDate(new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date()));
        nettyMessageDO.setDeviceName(DEVICENAME);
        Message.MessageBase.Builder authMsg = Message.MessageBase.newBuilder();
        authMsg.setClientId(CLIENTID);
        authMsg.setCmd(Command.CommandType.AUTH);
        authMsg.setData(JSON.toJSONString(nettyMessageDO));
        ctx.writeAndFlush(authMsg.build());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.debug("发生异常   "+cause.getMessage());
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {

    }
}
